package com.xijia.proxy.jdk;

import com.xijia.proxy.ext.ExtAsync;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * jdk 动态代理执行方法，判断是否为 ExtAsync 异步操作
 * @author wangsong
 * @mail 1720696548@qq.com
 * @date 2020/8/30 0030 20:55
 * @version 1.0.0
 */
public class MayiktInvocationHandler implements InvocationHandler {
    /**
     * 目标对象
     */
    private Object target;

    /**
     * 定义线程池
     */
    private ExecutorService executorService;

    public MayiktInvocationHandler(Object target) {
        this.target = target;
        executorService = Executors.newFixedThreadPool(10);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //使用反射技术执行目标方法
//        ExtAsync extAsync = method.getDeclaredAnnotation(ExtAsync.class);
        //根据接口的信息查找到目标对象的的方法
        Method methodImpl = target.getClass().getMethod(method.getName(), method.getParameterTypes());
        ExtAsync extAsync = methodImpl.getDeclaredAnnotation(ExtAsync.class);
        if (extAsync == null) {
            // 该方法上没有加上异步注解，则直接调用目标方法
            return method.invoke(target, args);
        }
        // 单独开启一个线程异步处理目标方法
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    method.invoke(target, args);
                } catch (Exception e) {

                }

            }
        });
        return null;
    }

    /**
     * 生成代理类
     *
     * @param <T>
     * @return
     */
    public <T> T getProxy() {
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }
}
